<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'/>
    <meta name="viewport" content="viewport-fit=cover, width=device-width,  height=device-height, initial-scale=1, user-scalable=no">
  </head>
  <body style="background-color: transparent" autocorrect="off">
    <div id="terminal"
         style="width:100%; height:100%; background-color: transparent"></div>
  </body>

  <script src="hterm/hterm_all.js"></script>

  <style>
      html,
      body {
        height: 100%;
        width: 100%;
        overflow: auto;
      }
  </style>
  
  <script>
    var t = null;
    
    var urls = [];

    const esc = `\x1b`;
    const bel = `\x07`;
    
    const sgr = (...args) => `${esc}[${args.join(';')}m`;
    
    const underline = sgr(4);

    const osc = (...args) => `${esc}]${args.join(';')}${bel}`;
    const osc8 = (uri='', params='') => osc(8, params, uri);
    
    const normal = sgr(0);
    
    const bullet = '\u{2022}';
    
    var outputHistory = "";
    
    window.openUrl = function (url) {
        var link = null;
        if (isNaN(parseInt(url))) {
            link = url;
        } else {
            link = urls[parseInt(url)];
        }
        
        window.webkit.messageHandlers.pyto.postMessage("openlink:"+link);
    }
    
    function getContentHeight() {
      var i = t.screen_.rowsArray.length;

      var continue_ = true;
      t.screen_.rowsArray.slice().reverse().forEach(function(entry) {

        if (!continue_) { return; }
          
        if (entry.innerText == "") {
          i -= 1;
        } else {
          continue_ = false;
        }
      });

      return (t.scrollPort_.characterSize.height*i)+5;
    }
  
    function sendSize() {
      window.webkit.messageHandlers.pyto.postMessage("size:"+JSON.stringify({width:t.screenSize.width, height:t.screenSize.height, charHeightSize: t.scrollPort_.characterSize.height}));
    }
  
    function printLink(text, link) {
      var _link = decodeURIComponent(escape(window.atob(link)));
      var _text = decodeURIComponent(escape(window.atob(text)));
      _text = "\x1b[32m"+_text+"\x1b[39m";
      urls.push(_link)
      output = `${underline}${osc8(urls.length-1)}${_text}${osc8()}${normal}`;
      outputHistory += output;
      t.io.print(output);
      console.log(output);
    }
    
    function print(text) {
      var output = decodeURIComponent(escape(window.atob(text)));
      outputHistory += output;
      t.io.print(output);
    }
  
    function showImage(image) {
      t.displayImage({uri:image, inline:true});
    }
    
    function numberOfRowsAfterPrompt() {
        var numberOfRows = 0;
        var i = 1;
        while (t.document_.querySelectorAll("x-row")[t.getCursorRow()+i] !== undefined) {
            i += 1;
            numberOfRows += 1;
        }
        return numberOfRows;
    }
    
    function setupHterm() {
      t = new hterm.Terminal();
      t.prefs_.set('cursor-shape', 'BLOCK');
      t.prefs_.set('enable-clipboard-notice', false);
      t.prefs_.set('use-default-window-copy', true);
      t.prefs_.set('clear-selection-after-copy', false);
      t.prefs_.set('copy-on-select', false);
      t.prefs_.set('audible-bell-sound', '');
      t.prefs_.set('meta-sends-escape', 'false');
      t.prefs_.set('terminal-encoding', 'utf-8');
      t.prefs_.set('enable-resize-status', true);
      t.prefs_.set('allow-images-inline', true);
      
      t.setReverseWraparound(true);
      t.setWraparound(true);
      
      t.onTerminalReady = function() {
        const io = t.io.push();
        
        io.onTerminalResize = (columns, rows) => {
          sendSize();
        };
        
        io.onVTKeystroke = (string) => {
          window.webkit.messageHandlers.pyto.postMessage(string);
        };
        
        sendSize();
        
        t.document_.body.style.caretColor = "transparent";
        t.document_.querySelector("x-screen").setAttribute("autocomplete", "off");
        t.document_.querySelector("textarea").setAttribute("autocomplete", "off");
        
        t.document_.addEventListener("click", function (event) {
          if (event.target.tagName == "IMG") {
              var images = Array.prototype.slice.call(t.document_.querySelectorAll("img"));
              var message = {
                index: images.indexOf(event.target),
                images: images.map(function (img) { return img.src })
              }
              
              window.webkit.messageHandlers.pyto.postMessage(message);
          }
        });
      };

      t.setWindowTitle = function (title) {
        window.webkit.messageHandlers.pyto.postMessage({title: title});
      };
      
      t.decorate(document.querySelector('#terminal'));

      if (window.voiceOver != undefined) {
        t.setAccessibilityEnabled(window.voiceOver);
      }
      
      t.installKeyboard();
      
      var a = false;
      document.getElementById("terminal").addEventListener('wheel', function(event) {
        
        if (a) {
            a = false;
            return;
        }
        
        a = true;
        
        var intDelta = Math.ceil(event.deltaY);
        
        intDelta = intDelta/4;
        intDelta = Math.ceil(intDelta);
        
        if (intDelta < 0) {
            intDelta = intDelta * (-1);
        }
        
        console.log(intDelta);
        
        var i = 0
        while (i <= intDelta) {
            if (event.deltaY > 0) {
                t.scrollLineDown();
            } else {
                t.scrollLineUp();
            }
            i += 1;
        }
        
        return false;
      }, false);
    }

    // This will be whatever normal entry/initialization point your project uses.
    window.onload = async function() {
      await lib.init();
      setupHterm();
    };
  </script>
</html>
